package com.zzw.easyexcel;

import com.alibaba.excel.write.handler.RowWriteHandler;
import com.alibaba.excel.write.handler.context.RowWriteHandlerContext;
import org.apache.poi.ss.usermodel.Row;
import org.apache.poi.ss.usermodel.Sheet;
import org.apache.poi.ss.util.CellRangeAddress;

/**
 * @author Administrator
 */
public class DefaultRowWriteHandler implements RowWriteHandler {

    private final int cycle;
    private final Integer[] mergeColumnIndex;

    public DefaultRowWriteHandler(int cycle, Integer[] mergeColumnIndex) {
        this.cycle = cycle;
        this.mergeColumnIndex = mergeColumnIndex;
    }

    @Override
    public void afterRowDispose(RowWriteHandlerContext context) {
        if (cycle == 0) {
            return;
        }
        Row currentRow = context.getRow();
        int currentRowIndex = currentRow.getRowNum();
        Sheet sheet = context.getWriteSheetHolder().getSheet();
        if (currentRowIndex == 0) {
            return;
        }
        if (currentRowIndex % cycle == 0) {
            for (int columnIndex : mergeColumnIndex) {
                if (cycle > 1) {
                    sheet.addMergedRegionUnsafe(new CellRangeAddress(currentRowIndex - cycle + 1, currentRowIndex, columnIndex, columnIndex));
                }
            }
        }
    }
}
